package com.lin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.entity.Department;
import com.lin.entity.Device;
import com.lin.mapper.DeviceMapper;
import com.lin.service.DeviceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 气体安全检测小组
 * @since 2022-06-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Resource
    DepartmentServiceImpl departmentService;

    @Override
    public List<Device> getDeviceList(Integer departmentDid, String key) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(departmentDid != 0, Device::getDepartmentDid, departmentDid).like(StringUtils.isNotBlank(key), Device::getCode, key);
        return list(queryWrapper);
    }

    @Override
    public Boolean addDevice(Device device) {
        //检查字段完整性
        if (device.getCode() == null || device.getName() == null || device.getName().isEmpty() || device.getCode().isEmpty())
            return false;//这里应该抛出异常，这里先false处理
        return this.save(device);
    }

    @Override
    public List getDeviceInfo(Integer departmentDid) {
        //查询部门信息
        List<Department> departments = departmentService.list(
                new QueryWrapper<Department>().eq(departmentDid != 0, "did", departmentDid));
        List<Map> maps = new ArrayList<>();
        for (Department department : departments) {
            LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Device::getDepartmentDid, department.getDid());
            List<Device> list = list(queryWrapper);
            HashMap map = new HashMap<>();
            map.put("department", department.getName());
            map.put("Device", list);
            maps.add(map);
        }
        return maps;
    }

    @Override
    public Boolean updateDevice(Device device) {
        return this.updateById(device);
    }

    @Override
    public Boolean removeDevice(Integer id) {
        return this.removeById(id);
    }
}
